package com.cloudwise.gproject.aop;

import com.cloudwise.gproject.dao.OlogDao;
import com.cloudwise.gproject.entity.Log;
import com.cloudwise.gproject.entity.Olog;
import com.cloudwise.gproject.entity.User;
import com.cloudwise.gproject.service.LogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;


/**
 * @author ：卫子健
 * @date ：Created in 2021/3/22 13:25
 * @description：日志操作监控aop
 * @modified By：
 * @version:
 */
@EnableAspectJAutoProxy
@Component
@Aspect//切面配置
public class LogHandlerAop {

    @Resource
    LogService logService;
    @Resource
    OlogDao ologDao;
    //登录日志切入点
    @Pointcut(value = "execution(* com.cloudwise.gproject.controller.*.*(..))")//切入点配置
    public void pointA(){}

    //操作日志切入点
    @Pointcut(value = "execution(* com.cloudwise.gproject.service.impl.*.insert*(..)) " +
            "|| execution(* com.cloudwise.gproject.service.impl.*.update*(..))" +
            "|| execution(* com.cloudwise.gproject.service.impl.*.delete*(..))")//切入点配置
    public void pointB(){}

    //登录日志记录
    @AfterReturning(value = "pointA()")//后置增强配置
    public void after1(JoinPoint joinPoint){
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();
        HttpSession session = request.getSession();
        User userinfo = (User)session.getAttribute("userInfo");
        if (userinfo!=null){
            //获取用户名
            String userName = userinfo.getUserName();
            //获取登录名
            String loginName = userinfo.getLoginName();
            String ip = request.getRemoteAddr();
            //获取被执行的方法的名字
            String methodName = joinPoint.getSignature().getName();
            //获取被执行的类的全类名
            String className = joinPoint.getTarget().getClass().getName();
            //获取被执行方法的参数
//            Object[] args = joinPoint.getArgs();
//            String params = Arrays.toString(args);
            ArrayList<String> strings = new ArrayList<>();
            Enumeration<String> parameterNames = request.getParameterNames();
            while (parameterNames.hasMoreElements()){
                String parametername = parameterNames.nextElement();
                String parameterkey = request.getParameter(parametername);
                strings.add(parametername+"="+parameterkey);
            }
            String params = strings.toString();
            //将获取的数据装载到Log实体类中
            Log log = new Log(loginName,userName,ip,className,methodName,params);
            //将数据插入到数据库
            logService.insert(log);
        }
    }

    //登录日志记录
    @AfterReturning(value = "pointB()")//后置增强配置
    public void after3(JoinPoint joinPoint){
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();
        HttpSession session = request.getSession();
        User userinfo = (User)session.getAttribute("userInfo");

        Olog olog = new Olog();
        olog.setTitle("商标注册");
        olog.setOperatorType(1);
        olog.setOperName(userinfo.getLoginName());
        olog.setOperTime(new Date());
        olog.setDeptName("开发部门");
        olog.setOperUrl(request.getRequestURL().toString());
        olog.setOperIp(request.getRemoteAddr());
        olog.setOperLocation("云智慧");
        //获取参数
        ArrayList<String> strings = new ArrayList<>();
        Object[] args = joinPoint.getArgs();
        if (args!=null&&args.length>0){
            for (Object arg : args) {
                String param = arg.getClass().getSimpleName()+arg;
                strings.add(param);
            }
        }
        olog.setOperParam(strings.toString());
        olog.setMethod(joinPoint.getSignature().getName());
        olog.setStatus(0);
        if (joinPoint.getSignature().getName().contains("insert")){
            olog.setBusinessType(1);
        }else if (joinPoint.getSignature().getName().contains("update")){
            olog.setBusinessType(2);
        }else {
            olog.setBusinessType(3);
        }
        ologDao.insert(olog);
    }

    @AfterThrowing(value = "pointB()",throwing = "ex")
    public void after4(JoinPoint joinPoint,Exception ex){
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();
        HttpSession session = request.getSession();
        User userinfo = (User)session.getAttribute("userInfo");

        Olog olog = new Olog();
        olog.setTitle("商标注册");
        olog.setOperatorType(1);
        olog.setOperName(userinfo.getLoginName());
        olog.setOperTime(new Date());
        olog.setDeptName("开发部门");
        olog.setOperUrl(request.getRequestURL().toString());
        olog.setOperIp(request.getRemoteAddr());
        olog.setOperLocation("云智慧");
        //获取参数
        ArrayList<String> strings = new ArrayList<>();
        Object[] args = joinPoint.getArgs();
        if (args!=null&&args.length>0){
            for (Object arg : args) {
                String param = arg.getClass().getSimpleName()+arg;
                strings.add(param);
            }
        }

        olog.setOperParam(strings.toString());
        olog.setMethod(joinPoint.getSignature().getName());
        olog.setStatus(1);
        olog.setErrorMsg(ex.getMessage());
        if (joinPoint.getSignature().getName().contains("insert")){
            olog.setBusinessType(1);
        }else if (joinPoint.getSignature().getName().contains("update")){
            olog.setBusinessType(2);
        }else {
            olog.setBusinessType(3);
        }
        ologDao.insert(olog);
    }

    //操作日志记录

//    @Around("pointB()")//环绕增强配置
//    public Object araound(ProceedingJoinPoint proceedingJoinPoint,JoinPoint joinPoint)  {
//        Object proceed = null;
//        System.out.println("----环绕通知----");
//        Olog olog = new Olog();
//        try {
//            RequestAttributes ra = RequestContextHolder.getRequestAttributes();
//            ServletRequestAttributes sra = (ServletRequestAttributes) ra;
//            HttpServletRequest request = sra.getRequest();
//            HttpSession session = request.getSession();
//            User userinfo = (User)session.getAttribute("userInfo");
//
//            olog.setTitle("商标注册");
//            olog.setOperatorType(1);
//            olog.setOperName(userinfo.getLoginName());
//            olog.setOperTime(new Date());
//            olog.setDeptName("开发部门");
//            olog.setOperUrl(request.getRequestURL().toString());
//            olog.setOperIp(request.getRemoteAddr());
//            olog.setOperLocation("云智慧");
//            //获取参数
//            ArrayList<String> strings = new ArrayList<>();
//            Object[] args = joinPoint.getArgs();
//            if (args!=null&&args.length>0){
//                for (Object arg : args) {
//                    String param = arg.getClass().getSimpleName()+arg;
//                    strings.add(param);
//                }
//            }
//            olog.setOperParam(strings.toString());
//            olog.setMethod(joinPoint.getSignature().getName());
//            //调用业务方法（被增强的方法）
//            proceed = proceedingJoinPoint.proceed();
//            olog.setStatus(0);
//        } catch (Throwable e) {
//            olog.setErrorMsg(e.getMessage());
//            olog.setStatus(1);
//            e.printStackTrace();
//        }finally {
//            ologDao.insert(olog);
//        }
//        return proceed;
//
//    }
}
